﻿#include <cstdio>
#include "uart.h"

#define ATE1_COMMAND               "ATE1"
#define AT_CPIN_COMMAND            "AT+CPIN?"
#define AT_CSQ_COMMAND             "AT+CSQ"
#define MCU_DEFAULT_MAX_SIZE       512

int send(int fd, const char* command, int length);

int main()
{
    int fd = SerialPort::openUart("/dev/ttyUSB3");
    if (fd < 0)
    {
        printf("SerialPort openUart error,fid:%d\n", fd);
        return -1;
    }

    {
        send(fd, ATE1_COMMAND, strlen(ATE1_COMMAND));

        usleep(1000);
        char buffer[MCU_DEFAULT_MAX_SIZE] = { 0 };
        int length = SerialPort::readUart(fd, buffer, sizeof(buffer));
        if (length <= 0)
        {
            printf("4g model read \"%s\" error,ret:%d\n", ATE1_COMMAND, length);
            SerialPort::closeUart(fd);
            sleep(1);
            return -2;
        }

        printf("%s\n", buffer);
    }


    {
        send(fd, AT_CSQ_COMMAND, strlen(AT_CSQ_COMMAND));

        usleep(1000);
        char buffer[MCU_DEFAULT_MAX_SIZE] = { 0 };
        int length = SerialPort::readUart(fd, buffer, sizeof(buffer));
        if (length <= 0)
        {
            printf("4g model read \"%s\" error,ret:%d\n", AT_CSQ_COMMAND, length);
            SerialPort::closeUart(fd);
            sleep(1);
            return -2;
        }

        printf("%s\n", buffer);
    }



    {
        send(fd, AT_CPIN_COMMAND, strlen(AT_CPIN_COMMAND));

        usleep(1000);
        char buffer[MCU_DEFAULT_MAX_SIZE] = { 0 };
        int length = SerialPort::readUart(fd, buffer, sizeof(buffer));
        if (length <= 0)
        {
            printf("4g model read \"%s\" error,ret:%d\n", AT_CPIN_COMMAND, length);
            SerialPort::closeUart(fd);
            sleep(1);
            return -2;
        }

        printf("%s\n", buffer);
    }

    printf("%s 向你问好!\n", "FiboConsole");

    return 0;

}


int send(int fd, const char* command, int length)
{
    try
    {
        if (length <= 0 || command == NULL)
        {
            return -1;
        }

        char command2[30] = { 0 };

        memcpy(command2, command, length);
        command2[length] = '\x0D'; length++;
        command2[length] = '\x0A'; length++;

        int ret = SerialPort::writeUart(fd, command2, length);

        if (ret >= 1)
        {
            return ret;
        }
    }
    catch (...)
    {

    }

    return -1;

}